<?php

namespace app\api\logic;

use \app\common\model\CourseChapter as CourseChapterModel;
use \app\common\model\CourseChapterSection as CourseChapterSectionModel;
use app\common\model\CourseQuestion;

class ChapterQuestion
{
    /**
     * 章节题目(一级列表)
     * @param $param
     * @return array
     */
    public function getList($param): array
    {
        // 提取参数
        $course_id = $param['course_id'];

        // 查询数据
        $field = 'a.id,a.name,b.code';
        $list = app(CourseChapterModel::class)->getListByCourseId($course_id, $field);
        foreach ($list as $key => $val) {
            $list[$key]['is_open'] = 0;
            $list[$key]['section'] = [];
        }

        // 提取主键,批量查询二级目录
        $mainIds = array_column($list, 'id');
        if ($mainIds) {
            $field = 'id,pid,name,count';
            $sectionList = app(CourseChapterSectionModel::class)->getListByPid($mainIds, $field);

            // 查询小节题目数量
            if ($sectionList) {
                $sectionIds = array_column($sectionList, 'id');
                $sectionQuestionCountList = app(CourseQuestion::class)->getExtendQuestionCount($course_id, $sectionIds);
                $sectionQuestionCountDict = array_dict($sectionQuestionCountList, 'extend_id');
            }

            // 循环处理数据
            foreach ($sectionList as $key1 => $val1) {
                $id = $val1['id'];
                $count = $sectionQuestionCountDict[$id]['count'] ?? 0;
                $val1['count'] = $count;
                $val1['max_page'] = ceil($count / 10);
                foreach ($list as $key2 => $val2) {
                    if ($val2['id'] == $val1['pid']) {
                        $list[$key2]['section'][] = $val1;
                        break;
                    }
                }
            }
        }

        //组装数据
        return $list;
    }

}